<template>
  <view class="main">
    <view class="title">
      <uni-icons color="black" size="28" type="left" @tap="goBack"></uni-icons>
      <!-- 站位 -->
      <view v-if="showMore">更多搜索结果</view>
      <view v-else></view>
      <uni-icons type="help" size="28" color="black" @tap="goHelp"></uni-icons>
    </view>

    <view v-show="!showMore" class="main_content">
      <view v-show="searchStop || searchNone" class="not_search">
        <image class="image" src="@/static/ring/connect/ble_ring.png" mode="widthFix"></image>
        <view class="tip1">连接戒指，开启健康生活</view>
        <view class="tip2">
          收到戒指后，需将戒指放在充电盒内<br />
          充电激活后连接！
        </view>

        <view class="btn" @click="startSearch">连接您的戒指</view>
      </view>

      <view v-show="searching" class="search_ing">
        <image class="image" src="http://qiniu.relaverse.cn/icon/ring_into_box.gif" mode="widthFix"></image>

        <view class="btn">搜索中...</view>

        <view class="tip">
          注：戒指內圈二維碼下方7位數字 <br />
          後4位為該戒指編號
        </view>
      </view>

      <view v-show="searchDone" class="search_done">
        <image class="image" src="@/static/ring/connect/ring.png" mode="widthFix"></image>
        <view class="name">{{ signalFirstDevice.name || signalFirstDevice.localName }}</view>
        <view class="mac">
          {{ signalFirstDevice.mac }}
          <div class="signal-icon">
            <div :class="['signal-bar', 'bar-1', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 1}]"></div>
            <div :class="['signal-bar', 'bar-2', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 2}]"></div>
            <div :class="['signal-bar', 'bar-3', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 3}]"></div>
            <div :class="['signal-bar', 'bar-4', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 4}]"></div>
            <div :class="['signal-bar', 'bar-5', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 5}]"></div>
          </div>
        </view>
        <!-- :class="[isConnect, connectId === signalFirstDevice.deviceId ? 'linkSelf' : '']" -->
        <view class="btn" :class="{ isBinding, linkSelf: connectId === signalFirstDevice.deviceId }" @click="connect(signalFirstDevice)">{{
            linkSelf(signalFirstDevice.deviceId)
          }}</view>
        <view class="again" @click="research">沒找到我的戒指，重新搜索</view>

        <view v-if="deviceMore2" class="list">
          <view class="item" v-for="(item, index) in otherDevices.filter((_, i) => i < 2)" :key="index">
            <image class="img" src="@/static/ring/connect/ring.png" mode="widthFix"></image>
            <view class="info">
              <view class="name">{{ item.name || item.localName }}</view>
              <view class="mac">
                {{ item.mac }}
                <div class="signal-icon">
                  <div :class="['signal-bar', 'bar-1', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 1}]"></div>
                  <div :class="['signal-bar', 'bar-2', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 2}]"></div>
                  <div :class="['signal-bar', 'bar-3', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 3}]"></div>
                  <div :class="['signal-bar', 'bar-4', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 4}]"></div>
                  <div :class="['signal-bar', 'bar-5', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 5}]"></div>
                </div>
              </view>
            </view>
            <view class="link" :class="{ isBinding, linkSelf: connectId === item.deviceId }" @click="connect(item)">{{
                linkSelf2(item.deviceId)
              }}</view>
          </view>

          <view v-if="deviceMoreThan3" class="more" @click="showMore = true"
          >查看更多搜索结果 <uni-icons color="#2D99FF" size="12" type="right"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <scroll-view scroll-y class="scroll" v-show="showMore">
      <view class="list">
        <view class="item" v-for="(item, index) in deviceList" :key="index">
          <image class="img" src="@/static/ring/connect/ring.png" mode="widthFix"></image>
          <view class="info">
            <view class="name">{{ item.name || item.localName }}</view>
            <view class="mac">
              {{ item.mac }}
              <div class="signal-icon">
                <div :class="['signal-bar', 'bar-1', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 1}]"></div>
                <div :class="['signal-bar', 'bar-2', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 2}]"></div>
                <div :class="['signal-bar', 'bar-3', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 3}]"></div>
                <div :class="['signal-bar', 'bar-4', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 4}]"></div>
                <div :class="['signal-bar', 'bar-5', {'filled': getSignalBars(signalFirstDevice.RSSI) >= 5}]"></div>
              </div>
            </view>
          </view>
          <view class="link" :class="{ isBinding, linkSelf: connectId === item.deviceId }" @click="connect(item)">{{ linkSelf2(item.deviceId) }}</view>
        </view>
        <image class="no_more" src="@/static/ring/connect/no_other_ring.png" mode="widthFix"></image>
      </view>
    </scroll-view>

    <!-- <view v-if="showAuthDialog" class="dialog">
        <view class="body">
            <view v-if="!authMap.gps" @click="toGps"> GPS服务未开启 </view>

            <view v-if="!authMap.userLocation" @click="toUserGps"> 位置未授权 </view>

            <view v-if="!authMap.bluetooth" @click="toBluetooth"> 蓝牙未开启 </view>

            <view v-if="!authMap.userBluetooth" @click="toUserBlue"> 蓝牙未授权 </view>
        </view>
    </view> -->

    <BottomDrawer v-model="unAvailableDrawer" :show-title="false" maskBg="rgba(19, 19, 19, 0.9)">
      <view class="no_find_drawer">
        <view class="top_tips">未开启蓝牙，请开启蓝牙后连接</view>
        <view class="bottom_tips"> 未开启蓝牙将无法连接并使用戒指 </view>
        <view class="btn_warp">
          <RSButton :height="'80rpx'" type="google" width="45%" @tap="unAvailableDrawer = false"> 暂不开启 </RSButton>
          <RSButton :height="'80rpx'" type="primary" width="45%" @tap="toOpenPerm"> 前往开启 </RSButton>
        </view>
      </view>
    </BottomDrawer>

    <BottomDrawer v-model="searchNoneDrawer" :show-title="false" maskBg="rgba(19, 19, 19, 0.9)">
      <view class="no_find_drawer">
        <view class="top_tips">抱歉，我们没有找到任何戒指</view>
        <view class="bottom_tips"> 如果你遇到任何问题，请阅读连接说明或联系我们：support@dering.io。 </view>
        <view class="btn_warp">
          <RSButton :height="'80rpx'" type="google" width="45%" @tap="goBack"> 好的 </RSButton>
          <RSButton :height="'80rpx'" type="primary" width="45%" @tap="research"> 重新搜索 </RSButton>
        </view>
      </view>
    </BottomDrawer>

    <BottomDrawer v-model="bindErrorDrawer" :show-title="false" maskBg="rgba(19, 19, 19, 0.9)">
      <view class="no_find_drawer">
        <view class="top_tips">无法连接。</view>
        <view class="bottom_tips"> {{ bindError }} </view>
        <view class="btn_warp">
          <RSButton :height="'80rpx'" type="google" width="100%" @tap="bindErrorDrawer = false"> 好的 </RSButton>
        </view>
      </view>
    </BottomDrawer>

    <view v-if="showSuccessDialog" class="success-dialog">
      <view class="dialog-title">戒指已连接成功</view>
      <image class="dialog-image" src="/static/ring/ring.png" ></image>
      <view class="dialog-text">开启您的健康之旅吧</view>
      <view class="dialog-button" @click="closeSuccessDialog">确定</view>
    </view>
  </view>
</template>
<script>
import store from "@/store/index";
import { SEARCH_STATUS, BLUETOOTH_STATUS } from "@/store/BluetoothManager.js";
import BottomDrawer from "@/components/drawer/BottomDrawer.vue";
import RSButton from "./components/drawer/RSButton.vue";
import { bindUserRing } from "@/api/ring/bind.js";
import { getUserRing } from "@/utility/business.js";
import { setWithExpiration } from "@/js_sdk/utils/expiration.js";

export default {
  components: {
    BottomDrawer,
    RSButton,
  },
  data() {
    return {
      showMore: false,
      showAuthDialog: false,
      isHide: false,
      hideTime: 0,
      connectId: "",
      isBinding: false,
      // bluetoothStatus: 3,

      searchNoneDrawer: false,
      unAvailableDrawer: false,
      bindErrorDrawer: false,
      bindError: "",
      showSuccessDialog: false
    };
  },
  computed: {
    authMap() {
      return store.state.bleManage.authMap;
    },
    deviceList() {
      console.log(store.state.bleManage.devices)
      return store.state.bleManage.devices;
    },

    signalFirstDevice() {
      return (
          this.deviceList.reduce((first, current) => {
            if (!first) return current;
            if (first.RSSI >= current.RSSI) return first;
            else return current;
          }, null) || {}
      );
    },

    otherDevices() {
      return this.deviceList.filter((item) => item.deviceId !== this.signalFirstDevice.deviceId);
    },

    deviceMore2() {
      return this.deviceList.length >= 2;
    },

    deviceMoreThan3() {
      return this.deviceList.length >= 3;
    },

    searchStatus() {
      return store.state.bleManage.searchStatus;
    },

    /**
     * 未开启搜索
     */
    searchStop() {
      return this.searchStatus === SEARCH_STATUS.UNSEARCH;
    },

    /**
     * 搜索中
     */
    searching() {
      return this.searchStatus === SEARCH_STATUS.SEARCHING;
    },

    /**
     * 搜索完成 就是搜索到
     */
    searchDone() {
      return this.searchStatus === SEARCH_STATUS.FOUND;
    },

    /**
     * 没有搜索到
     */
    searchNone() {
      return this.searchStatus === SEARCH_STATUS.NOTFOUND;
    },

    bluetoothStatus() {
      return store.state.bleManage.bluetoothStatus;
    },

    isConnect() {
      return this.bluetoothStatus === BLUETOOTH_STATUS.CONNECTING || this.bluetoothStatus === BLUETOOTH_STATUS.CONNECTED;
    },

    linkSelf() {
      return (id) => {
        return id === this.connectId ? "连接中..." : "确认连接";
      };
    },
    linkSelf2() {
      return (id) => {
        return id === this.connectId ? "连接中..." : "连接";
      };
    },

    unAvailable() {
      return store.state.bleManage.available.slice(-1)[0] === false;
    },
  },

  watch: {
    searchStatus() {
      console.log(this.searchStatus);
    },

    searchNone() {
      if (this.searchNone) {
        this.searchNoneDrawer = true;
      }
    },
    unAvailable() {
      this.unAvailableDrawer = this.unAvailable;
    },
  },
  onLoad() {
    this.$store.dispatch("bleManage/changePage", "connect");
    this.checkPerm();
    console.log("触发第一次");
  },
  async onShow() {
    if (this.isHide && Date.now() - this.hideTime > 500) {
      await this.checkPerm();
      this.isHide = false;
      console.log("触发后续次数");
    }
  },
  onHide() {
    if (!this.isHide) {
      this.isHide = true;
      this.hideTime = Date.now();
    }
  },

  onUnload() {
    console.log("onUnload");
    this.$store.dispatch("bleManage/_stopScanDevices");
    this.$store.dispatch("bleManage/resetSearchState");
    this.$store.dispatch("bleManage/changePage", "main");
  },
  methods: {
    goBack() {
      if (this.showMore) {
        this.showMore = false;
        return;
      }
      uni.navigateBack();
    },
    goHelp() {},

    async startSearch() {
      try {
        await this.closeBlue();
        await this.initBlue();
        this.searchDevice();
      } catch (error) {
        console.log("startSearch error", error);
      }
    },

    async research() {
      this.searchNoneDrawer = false;
      this.startSearch();
    },
    async closeSuccessDialog(){
      this.$nextTick(() => {
        uni.navigateBack();

        setTimeout(() => {
          this.connectId = "";
        }, 500);
      });
    },
    async connect(device) {
      if (!device || !device.deviceId) return;
      this.connectId = device.deviceId;

      try {
        await bindUserRing({
          mac: device.mac,
          name: device.name,
          ringType: 3,
        });

        setWithExpiration("bind", 1, 360);
        this.$store.dispatch("bleManage/_stopScanDevices");

        await getUserRing();

        this.$store.dispatch("ringDataManage/setRing", {
          name: device.name,
          mac: device.mac,
        });

        this.$store.dispatch("bleManage/connectDevice", device);
        // 显示成功弹窗
        this.showSuccessDialog = true;
      } catch (error) {
        this.connectId = "";

        if (error.code === 300 && error.msg) {
          this.bindError = error.msg || "绑定失败，请联系客服";
          this.bindErrorDrawer = true;
        }
        /**
         * {
         *	"code": 300,
         *	"msg": "已绑定戒指:[AA:30:A0:06:9A:D7]",
         *	"data": null,
         *	"timestamp": 1742976924391,
         *	"success": false
         *}

         *	{
         *  "code": 300,
         *  "msg": "此戒指:[AA:30:A0:06:9A:D6]已被其他用户绑定",
         *  "data": null,
         *  "timestamp": 1742977057972,
         * "success": false
         *	}
         */
        console.log("connect error", error);
      }
    },

    async checkPerm() {
      const result = await this.$store.dispatch("bleManage/checkPermission");
      // const { gps, bluetooth, userLocation, userBluetooth } = result;
      // this.showAuthDialog = !gps || !bluetooth || !userLocation || !userBluetooth;
      console.log("auth result", result);
    },

    initBlue() {
      return this.$store.dispatch("bleManage/initBluetooth");
    },

    closeBlue() {
      return this.$store.dispatch("bleManage/closeBluetooth");
    },

    searchDevice() {
      this.$store.dispatch("bleManage/searchAllRingDevices");
      // this.$store.dispatch("bleManage/searchSpecifyRingDevice", "AA:30:A0:06:9A:D6");
    },

    toGps() {
      this.$store.dispatch("bleManage/intoSystemLocationSetting");
    },
    toUserGps() {
      this.$store.dispatch("bleManage/intoAppBluetoothSetting");
    },
    toBluetooth() {
      this.$store.dispatch("bleManage/intoSystemBluetoothSetting");
    },
    toUserBlue() {
      this.$store.dispatch("bleManage/intoAppBluetoothSetting");
    },
    async toOpenPerm() {
      const { gps, bluetooth, userLocation, userBluetooth } = await this.$store.dispatch("bleManage/checkPermission");
      console.log("permMap", {
        gps,
        bluetooth,
        userLocation,
        userBluetooth,
      });
      if (!userBluetooth || !userLocation) {
        this.$store.dispatch("bleManage/intoAppBluetoothSetting");
        return;
      }
      const platform = uni.getSystemInfoSync().platform;
      if (!bluetooth) {
        this.$store.dispatch("bleManage/intoSystemBluetoothSetting");
      }
      if (platform === "android" && !gps) {
        this.$store.dispatch("bleManage/intoSystemLocationSetting");
      }
    },
    getSignalBars(rssi) {
      if (rssi >= -50) {
        return 5;
      } else if (rssi >= -60) {
        return 4;
      } else if (rssi >= -70) {
        return 3;
      } else if (rssi >= -80) {
        return 2;
      } else {
        return 1;
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  padding-top: var(--status-bar-height);
  height: 100vh;
  background-color: #bbdcf5;

  .title {
    padding: 42rpx 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .left {
      font-size: 40rpx;
      font-weight: 500;
      color: #ffffff;
      padding: 22rpx 36rpx;
    }

    .right {
      font-size: 32rpx;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.3);
      padding-right: 36rpx;
    }
  }

  .main_content {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: black;
    text-align: center;
    font-size: 14px;
    font-style: normal;
    font-weight: 500;
    line-height: normal;

    height: calc(100% - var(--status-bar-height) - 42rpx - 64rpx);

    .not_search {
      width: 100vw;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;

      .image {
        width: 268rpx;
        margin-top: 120rpx;
      }

      .tip1 {
        width: 484rpx;
        font-weight: 500;
        font-size: 44rpx;
        line-height: 100%;
        text-align: center;
        color: black;
        margin-top: 40rpx;
      }

      .tip2 {
        width: 484rpx;
        font-weight: 400;
        font-size: 28rpx;
        line-height: 40rpx;
        text-align: center;
        margin-top: 20rpx;
      }

      .btn {
        margin-top: auto;
        margin-bottom: auto;
        width: 80%;
        height: 96rpx;
        border-radius: 20rpx;

        color: white;

        font-weight: 500;
        font-size: 20px;
        text-align: center;
        line-height: 96rpx;

        background-color: #2d99ff;
      }
    }

    .search_ing {
      width: 100vw;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-direction: column;

      .image {
        width: 500rpx;
        margin-top: 40rpx;
      }

      .btn {
        margin-top: 200rpx;
        width: 80%;
        height: 96rpx;
        border-radius: 20rpx;

        color: #2d99ff;

        font-weight: 500;
        font-size: 20px;
        text-align: center;
        line-height: 96rpx;

        border: 2rpx solid #2d99ff;
        background-color: white;
      }

      .tip {
        width: 350rpx;
        font-weight: 500;
        font-size: 24rpx;
        text-align: center;
        line-height: 40rpx;
        color: rgba(0, 0, 0, 0.5);
        margin-top: 20rpx;
      }
    }

    .search_done {
      width: 100vw;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-direction: column;

      .image {
        width: 268rpx;
        margin-top: 30rpx;
      }

      .name {
        font-weight: 500;
        font-size: 48rpx;
        line-height: 100%;
        margin-top: 30rpx;
      }

      .mac {
        font-weight: 400;
        font-size: 28rpx;
        margin-top: 20rpx;
        display: flex;
        align-items: center;
      }

      .btn {
        width: 80%;
        height: 96rpx;
        border-radius: 20rpx;

        margin-top: 80rpx;

        color: white;

        font-weight: 500;
        font-size: 20px;
        text-align: center;
        line-height: 96rpx;

        background-color: #2d99ff;
      }

      .again {
        color: #2d99ff;
        font-weight: 500;
        font-size: 12px;
        line-height: 100%;
        text-align: center;
        margin-top: 30rpx;
      }
    }
  }

  .list {
    width: 100%;
    padding: 0 40rpx;

    .item {
      width: 100%;
      // height: 96rpx;

      display: flex;
      justify-content: flex-start;
      align-items: center;

      margin-top: 40rpx;

      .img {
        width: 96rpx;
      }

      .info {
        margin-left: 12rpx;
        text-align: left;

        .name {
          font-size: 28rpx;
          font-weight: 500;
          margin-top: 0;
        }

        .mac {
          font-size: 24rpx;
          font-weight: 400;
          margin-top: 8rpx;
          display: flex;
          align-items: center;
        }
      }

      .link {
        width: 200rpx;
        height: 66rpx;
        line-height: 66rpx;
        background-color: #2d99ff;
        color: white;
        text-align: center;
        border: 2rpx solid #2d99ff;
        border-radius: 60rpx;
        margin-left: auto;
      }
    }

    .more {
      font-size: 28rpx;
      color: #2d99ff;
      margin-top: 40rpx;
    }

    .no_more {
      width: 100%;
      margin-top: 40rpx;
    }
  }

  .scroll {
    width: 100%;
    height: calc(100% - var(--status-bar-height) - 42rpx - 64rpx);
  }

  .isBinding {
    pointer-events: none;
    background-color: #cccccc !important;
    color: white !important;
    border-color: #cccccc !important;
    &.linkSelf {
      background-color: #2d99ff !important;
      border-color: #2d99ff !important;
      color: white !important;
    }
  }

  .dialog {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.5);

    display: flex;
    justify-content: center;
    align-items: center;
    .body {
      width: 80%;
      // height: max-content;
      height: 100px;
      background-color: white;

      color: black;

      view {
        margin-top: 40rpx;
      }
    }
  }

  .no_find_drawer {
    padding: 64rpx 0rpx;

    .top_tips {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
      color: black;

      font-size: 44rpx;
      font-weight: 500;
      text-align: center;
      margin-bottom: 40rpx;
      white-space: pre;

      .icon_info {
        transform: rotate(180deg);
        margin-right: 16rpx;
      }
    }

    .bottom_tips {
      color: black;
      text-align: center;
      font-family: "PingFang SC";
      font-size: 32rpx;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
      margin-bottom: 40rpx;

      .underline_font {
        text-decoration: underline;
      }
    }

    .btn_warp {
      display: flex;
      justify-content: space-between;

      .find_btn1 {
        margin-right: 40rpx;
        border-radius: 40rpx;
        background: rgba(255, 255, 255, 0.05);

        font-family: "PingFang SC";
        font-size: 32rpx;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }

      .find_btn2 {
        border-radius: 40rpx;
        background: #fff;
        font-family: "PingFang SC";
        font-size: 32rpx;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }
    }
  }

  .signal-icon {
    display: inline-flex;
    align-items: flex-end;
    margin-left: 10px;
  }

  .signal-bar {
    width: 2px;
    margin-right: 1px;
    background-color: white;
    border: 1px solid #ccc;
  }

  .signal-bar.filled {
    background-color: #00E97C;
  }

  .bar-1 {
    height: 2px;
  }

  .bar-2 {
    height: 4px;
  }

  .bar-3 {
    height: 6px;
  }

  .bar-4 {
    height: 8px;
  }
  .bar-5 {
    height: 10px;
  }
}
.success-dialog {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .dialog-title {
    font-size: 24px;
    font-weight: bold;
    color: white;
    margin-bottom: 20px;
  }

  .dialog-image {
    width: 200px;
    margin-bottom: 20px;
  }

  .dialog-text {
    font-size: 18px;
    color: white;
    margin-bottom: 20px;
  }

  .dialog-button {
    width: 150px;
    height: 40px;
    background-color: #2d99ff;
    color: white;
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    cursor: pointer;
  }
}
</style>
